package com.hao_family.atcrowdfunding.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hao_family.atcrowdfunding.beans.TAdmin;
import com.hao_family.atcrowdfunding.beans.TMenu;
import com.hao_family.atcrowdfunding.constant.AppConstant;
import com.hao_family.atcrowdfunding.service.AdminService;

@Controller
public class LoginController {
	
	@Autowired
	AdminService adminService;

	@PostMapping("/dologin")
	public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
			HttpSession session,Model model) {
		TAdmin admin = adminService.getAdminByUsernameAndPassword(username, password);
		if (admin==null) {
			model.addAttribute(AppConstant.MSG_IN_ERRORLOGIN, "帐号或密码错误！！");
			//在model中保存username用于回显
			model.addAttribute("username",username);
			return "forward:/login.jsp";
		}else {
			session.setAttribute(AppConstant.ADMIN_IN_SESSION, admin);
			return "redirect:/main.html";
		}
	}

	@GetMapping("/main.html")
	public String domain(HttpSession session,Model model) {
		TAdmin admin = (TAdmin) session.getAttribute(AppConstant.ADMIN_IN_SESSION);
		if (admin==null) {
			model.addAttribute(AppConstant.MSG_IN_ERRORLOGIN, "尚未登录，请登录");
			return "forward:/login.jsp";
		}else {
			List<TMenu> list = adminService.listMenus();
			session.setAttribute(AppConstant.MENULIST_IN_SESSION, list);
			return "main";
		}
	}
	
}
